import Vue from 'vue'
import Vuex from 'vuex'
import clone from '@/lib/clone';
import createId from '@/lib/createId';

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    layoutData: {
      needInit: true,
      interval: '',
      incomeSum: 0,
      payoutSum: 0
    },
    createTagFail: false,
    createRecordFail: false,
    recordList: [],
    payout_tagList: [],
    income_tagList: [],
    accountList: [],
    cur_record: {
      tag: { id: '0', text: '一般', name: 'default' },
      notes: '商品',
      type: '-',
      amount: 0,
      account: {text: '未分类', name: 'more', detail: '默认账户', type: '', rest: ''},
      createdAt: ''
    },
  } as RootState,
  mutations: {
    initLayoutData(){
      if(store.state.layoutData.needInit){
        const now = new Date()
        store.state.layoutData = {
          needInit: false, interval: `${now.getFullYear()}-${now.getMonth()+1}`, incomeSum: 0, payoutSum: 0
        }
      }
    },
    //recordList
    initRecordList(state){
      state.recordList = JSON.parse(window.localStorage.getItem('recordList') || '[]') as RecordItem[];
    },
    initCurRecord(state){
      state.cur_record = {
        tag: { id: '0', text: '一般', name: 'default' },
        notes: '',
        type: '-',
        amount: 0.00,
        account: {text: '未分类', name: 'more', detail: '默认账户', type: '', rest: ''},
        createdAt: ''
      }
    },
    createRecord(state) {
      store.state.createRecordFail = false;
      if(state.cur_record.amount === 0){
        store.state.createRecordFail = true;
        window.alert('添加失败！金额不能为0！')
      }else{
        const record2: RecordItem = clone(state.cur_record);
        state.recordList.push(record2);
        store.commit('saveRecords')
        window.alert('添加成功！')
        store.state.createRecordFail = false;
      }
    },
    saveRecords(state) {
      window.localStorage.setItem('recordList', JSON.stringify(state.recordList));
    },
    //tagList
    initTagList(state){
      state.payout_tagList = JSON.parse(window.localStorage.getItem('payout_tagList') || '[]');
      state.income_tagList = JSON.parse(window.localStorage.getItem('income_tagList') || '[]');
    },
    createTag(state, payload: { text: string, type: string }) {
      store.state.createTagFail = false
      const { text, type } = payload
      const tagList: Tag[] = type === '+' ? state.income_tagList : state.payout_tagList;
      const texts = tagList.map(item => item.text);
      if (texts.indexOf(text) >= 0) {
        store.state.createTagFail = true
      }else{
        const id = createId().toString();
        tagList.push({id, name: 'diy-tag', text: text});
        store.commit('saveTags');
      }
    },
    deleteTag(state, id: string) {
      const tagList: Tag[] = state.cur_record.type === '+' ? state.income_tagList : state.payout_tagList;
      let index = -1;
      for (let i = 0; i < tagList.length; i++) {
        if (tagList[i].id === id) {
          index = i;
          break
        }
      }
      if(index === -1){
        return window.alert('删除失败！没有找到该标签！');
      }
      tagList.splice(index, 1);
      store.commit('saveTags');
      window.alert('删除成功！')
    },
    updateTags(state, payload: { id: string, text: string } ) {
      const { id, text } = payload
      const tagList: Tag[] = state.cur_record.type === '+' ? state.income_tagList : state.payout_tagList;
      const idList = tagList.map(item => item.id);
      if (idList.indexOf(id) >= 0) {
        const names = tagList.map(item => item.text);
        if (names.indexOf(text) >= 0) {
          return window.alert('标签名重复！')
        } else {
          const tag = tagList.filter(item => item.id === id)[0];
          tag.text = text;
          store.commit('saveTags');
        }
      }
    },
    saveTags(state) {
      const tagList: Tag[] = state.cur_record.type === '+' ? state.income_tagList : state.payout_tagList;
      const localStorageKeyName = state.cur_record.type === '+' ? 'income_tagList' : 'payout_tagList';
      window.localStorage.setItem(localStorageKeyName, JSON.stringify(tagList));
    },
  },
  actions: {
  },
  modules: {
  }
})

export default store;
